package service

import (
	"geekbang-go-homework/module1/dao"
	"geekbang-go-homework/module1/errors"
)

type User struct {
	ID       int
	UserName string
}

// NewUserService 获取UserService
func NewUserService(user dao.UserDao) *UserService {
	return &UserService{user}
}

// UserService 用户服务
type UserService struct {
	user dao.UserDao
}

// Get 通过主键获取用户信息，未找到记录不处理
func (u *UserService) Get(id int) (*User, error) {
	re, err := u.user.Get(id)
	if err != nil {
		return nil, err
	}
	return &User{
		ID:       re.ID,
		UserName: re.UserName,
	}, nil
}

// GetDemotion 通过主键获取用户信息，未找到返回一个默认用户
func (u *UserService) GetDemotion(id int) (*User, error) {
	re, err := u.user.Get(id)
	if errors.IsErrNoRows(err) {
		return &User{
			ID:       -1,
			UserName: "默认用户",
		}, err
	}
	if err != nil {
		return nil, err
	}
	return &User{
		ID:       re.ID,
		UserName: re.UserName,
	}, nil
}
